package com.hmall.gateway.filters;

import lombok.Data;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.OrderedGatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * <自定义GatewayFilter>
 *     //TODO 需要在application.yaml里配置信息才能使用
 *     自定义GatewayFilter不是直接实现GatewayFilter，而是实现AbstractGatewayFilterFactory
 *     ！！该类的名称一定要以GatewayFilterFactory为后缀！
 */

/*//TODO 最简单的方式*/
//@Component
//public class PrintAnyGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
//    @Override
//    public GatewayFilter apply(Object config) {
//        return new OrderedGatewayFilter(new GatewayFilter() {
//            @Override
//            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//                // 获取请求
//                ServerHttpRequest request = exchange.getRequest();
//                // 编写过滤器逻辑
//                System.out.println("过滤器执行了");
//                // 放行
//                return chain.filter(exchange);
//            }
//        },1);//TODO 这样就省去了还需要继承order，给优先级了
//
//    }
//}

/*//TODO 这种过滤器还可以支持动态配置参数*/
@Component
public class PrintAnyGatewayFilterFactory extends AbstractGatewayFilterFactory<PrintAnyGatewayFilterFactory.Config> {

    @Override
    public GatewayFilter apply(Config config) {
        return new OrderedGatewayFilter(new GatewayFilter(){
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                String a = config.getA();
                String b = config.getB();
                String c = config.getC();
                System.out.println("a = " + a);
                System.out.println("b = " + b);
                System.out.println("c = " + c);
                System.out.println("print any filter running");
                return chain.filter(exchange);
            }
        }, 1);
    }

    @Data
    public static class Config{
        private String a;
        private String b;
        private String c;
    }

    public PrintAnyGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return List.of("a", "b", "c");
    }
}
